import React from 'react';
import Cropper from 'react-cropper';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import 'cropperjs/dist/cropper.css';
import style from './cutImg.css';

class CutImg extends React.Component {
  constructor(props) {
    super(props);
    this.cropImage = this.cropImage.bind(this);
  }

  cropImage() {
    if (this.cropper.getCroppedCanvas() === 'null') {
      return false;
    }
    const url = this.cropper.getCroppedCanvas().toDataURL();
    this.props.getCropData(url);
    fetch('https://upload.qiniu.com/putb64/-1/',
      {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/octet-stream',
          Authorization: `UpToken ${this.props.uploadToken}`,
        },
        body: url.split('base64,')[1],
      },
      )
      .then(res => res.json())
      .then((json) => {
        this.props.dispatch({
          type: 'physicianAuth/selectImage',
          payload: {
            key: json.key,
          },
        });
      })
      .catch((error) => { console.log(error); });
    this.props.dispatch(routerRedux.push('/physicianAuth'));
  }
  cancelImage() {
    this.props.dispatch(routerRedux.push('/physicianAuth'));
  }

  render() {
    return (
      <div>
        <div style={{ width: '100%' }}>
          <Cropper
            src={this.props.src}
            ref={(cropper) => {
              this.cropper = cropper;
            }}
            style={{ height: `${window.innerHeight}px`, width: '100%' }}
            aspectRatio={1 / 1}
            minCropBoxWidth={`${window.innerWidth}`}
            minCropBoxHeight={`${window.innerWidth}`}
            guides={false}
            background={false}
            viewMode={0}
            dragMode="move"
            cropBoxMovable={false}
          />
        </div>
        <div className={style.button}>
          <div className={style.cancel} onClick={this.cancelImage.bind(this)}>取消</div>
          <div className={style.ok} onClick={this.cropImage}>完成</div>
        </div>
      </div>
    );
  }
}

function mapStateToProps({ physicianAuth }) {
  return { physicianAuth };
}

export default connect(mapStateToProps)(CutImg);
